/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * File Name          : freertos.c
  * Description        : Code for freertos applications
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "FreeRTOS.h"
#include "task.h"
#include "main.h"
#include "cmsis_os.h"
#include "esp8266.h"
#include "oled.h"
#include "stdio.h"
#include "string.h"
#include "dht11.h"
#include "semphr.h"
#include "bh1750.h"
#include "show.h"
#include "timers.h"
#include "upload.h"
#include "control.h"
#include "link.h"
#include "queue.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
extern UART_HandleTypeDef huart2;
uint8_t menu=1;
uint8_t pdata[128]={0};
uint8_t buzzerflag=0;
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
info ttinfo={0};
/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN Variables */

/* USER CODE END Variables */
/* Definitions for defaultTask */
xQueueHandle uartHandle;
osThreadId_t defaultTaskHandle;
osThreadId_t f1TaskHandle;
osThreadId_t f2TaskHandle;
osThreadId_t f3TaskHandle;
osThreadId_t f4TaskHandle;
osThreadId_t f5TaskHandle;
SemaphoreHandle_t semhandle;
TimerHandle_t  datatimerhandle;
TimerHandle_t  buzzertimerhandle;
const osThreadAttr_t defaultTask_attributes = {
  .name = "defaultTask",
  .stack_size = 128 * 4*3,
  .priority = (osPriority_t) osPriorityNormal,
};

const osThreadAttr_t f1Task_attributes = {
  .name = "f1Task",
  .stack_size = 128 * 4*4,
  .priority = (osPriority_t) osPriorityNormal,
};

const osThreadAttr_t f3Task_attributes = {
  .name = "f3Task",
  .stack_size = 128 * 4,
  .priority = (osPriority_t) osPriorityNormal,
};

const osThreadAttr_t f2Task_attributes = {
  .name = "f2Task",
  .stack_size = 128 * 4,
  .priority = (osPriority_t) osPriorityNormal,
};

const osThreadAttr_t f4Task_attributes = {
  .name = "f4Task",
  .stack_size = 128 * 4*2,
  .priority = (osPriority_t) osPriorityNormal1,
};

const osThreadAttr_t f5Task_attributes = {
  .name = "f5Task",
  .stack_size = 128 * 4*4,
  .priority = (osPriority_t) osPriorityNormal,
};

/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN FunctionPrototypes */

/* USER CODE END FunctionPrototypes */

void StartDefaultTask(void *argument);
void f1task(void*arg);
void f2task(void*arg);
void f3task(void*arg);
void f4task(void*arg);
void f5task(void*arg);
void readbuffer(uint8_t*m);
uint8_t  key_stat(void);
void time_increase(TimerHandle_t xTimer);
void buzzer_increase(TimerHandle_t xTimer);
void MX_FREERTOS_Init(void); /* (MISRA C 2004 rule 8.1) */

/**
  * @brief  FreeRTOS initialization
  * @param  None
  * @retval None
  */
void MX_FREERTOS_Init(void) {
  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* USER CODE BEGIN RTOS_MUTEX */
  /* add mutexes, ... */
  /* USER CODE END RTOS_MUTEX */

  /* USER CODE BEGIN RTOS_SEMAPHORES */
  /* add semaphores, ... */
    

  /* USER CODE END RTOS_SEMAPHORES */

  /* USER CODE BEGIN RTOS_TIMERS */
  /* start timers, add new ones, ... */
	int data=1;
	  datatimerhandle=xTimerCreate("data",1000,pdTRUE,&data,time_increase);
	int data2=1;
   buzzertimerhandle=xTimerCreate("data1",1,pdTRUE,&data2,buzzer_increase);
  /* USER CODE END RTOS_TIMERS */

  /* USER CODE BEGIN RTOS_QUEUES */
  /* add queues, ... */
	uartHandle=xQueueCreate(5,sizeof(pdata));
  /* USER CODE END RTOS_QUEUES */

  /* Create the thread(s) */
  /* creation of defaultTask */
  defaultTaskHandle = osThreadNew(StartDefaultTask, NULL, &defaultTask_attributes);

  /* USER CODE BEGIN RTOS_THREADS */
  /* add threads, ... */
  /* USER CODE END RTOS_THREADS */

  /* USER CODE BEGIN RTOS_EVENTS */
  /* add events, ... */
  /* USER CODE END RTOS_EVENTS */

}

/* USER CODE BEGIN Header_StartDefaultTask */
/**
  * @brief  Function implementing the defaultTask thread.
  * @param  argument: Not used
  * @retval None
  */
/* USER CODE END Header_StartDefaultTask */
void StartDefaultTask(void *argument)
{
  /* USER CODE BEGIN StartDefaultTask */
  /* Infinite loop */
	esp8266_init();
	OLED_Init();
	OLED_Clear();
	dht11_init();
	semhandle=xSemaphoreCreateBinary();
	xSemaphoreGive(semhandle);
	OLED_ShowString(0,0,(uint8_t*)"[1]INIT OK",16);
	
	if(esp8266_link_wifi(PID,PASSWARD))
	{
	    OLED_ShowString(0,2,(uint8_t*)"[2]CONN OK",16);

	}
	else
	{
	   OLED_ShowString(0,2,(uint8_t*)"[2]CONN ERR",16);
	}
	
	if(esp8266_connect_MQTT(MQTTIP,MQTTPORT,"zjw","zjw"))
	{
	
	  OLED_ShowString(0,4,(uint8_t*)"[3]CONN MQTT OK",16);
	
	
	}
	else
	{
	  OLED_ShowString(0,4,(uint8_t*)"[3]CONN MQTT ERR",16);
	
	}
	 if(esp8266_subscribe(TOPIC))
	  OLED_ShowString(0,6,(uint8_t*)"[4]MQTT SUB OK",16);

   else
		OLED_ShowString(0,6,(uint8_t*)"[4]MQTT SUB ERR",16); 
  osDelay(1000);
	f1TaskHandle= osThreadNew(f1task, NULL, &f1Task_attributes);
	 osDelay(1000);
  f2TaskHandle= osThreadNew(f2task, NULL, &f2Task_attributes);
  f3TaskHandle= osThreadNew(f3task, NULL, &f3Task_attributes);
	f4TaskHandle= osThreadNew(f4task, NULL, &f4Task_attributes);
  f5TaskHandle= osThreadNew(f5task, NULL, &f5Task_attributes);
	//osDelay(500);
	xTimerStart(datatimerhandle,portMAX_DELAY);
	HAL_UARTEx_ReceiveToIdle_IT(&huart2,pdata,sizeof(pdata));
	osDelay(500);
  for(;;)
  {  
		  if(key_stat()==1)
			{
				  if(buzzerflag==1)
					{
					   buzzer_stop();
					
					
					}
					else
					{
					 menu++;
				      if(menu==4)
				       {menu=1;}
					
					
					
					}
				     
				 

			}
			
			
			
			
			if(buzzerflag==0&&scan_alarmstat())
			{
			   buzzer_start();

			  
			}
		
		
		
		
		
    osDelay(50);
  }
  /* USER CODE END StartDefaultTask */
}

/* Private application code --------------------------------------------------*/
/* USER CODE BEGIN Application */
void f1task(void*arg)
{
 
   
	 
   uint8_t buffer[256]={0};
	 while(1)
	 {
	    //readbuffer(buffer);
		  xQueueReceive(uartHandle,buffer,portMAX_DELAY);
	   if(strlen((char*)buffer)>10)
		 {
			 //printf("get from server %s\r\n",buffer);
		   analysis_control((char*)buffer);
		  }
		  
		 memset(buffer,0,sizeof(buffer));

	 }

}
void readbuffer(uint8_t*m)
{    uint8_t i=0;
     uint8_t data,flag=0;
	   uint32_t old_tick=0;
  while (1)
  {
     if(HAL_GetTick()-old_tick>100&&flag)
		{
		
		   break;
		
		
		}
    if(HAL_UART_Receive(&huart2,(uint8_t*)&data,1,10)==HAL_TIMEOUT)
		{
		 continue;
		
		}
		else
		{	
		  m[i++]=data;
		  old_tick=HAL_GetTick();
			flag=1;
		
		}
	 
		
  }




}
void f2task(void*arg)
{
   uint8_t data[5]={0}; 
	while(1)
	{
	  vTaskSuspendAll();
	  dht11_send(data);
	  xTaskResumeAll(); 
		xSemaphoreTake(semhandle,portMAX_DELAY);
	  ttinfo.tmp=data[2];
		ttinfo.hum=data[0];
		xSemaphoreGive(semhandle);
	   
	  //printf("%d %d\r\n",data[0],data[2]);
		memset(data,0,sizeof(data));
		osDelay(500);
	}

}
void f3task(void*arg)
{

uint8_t data[2];
	uint16_t result;
  while (1)
  {
  
     WRITE_BH1750(0x20);
     HAL_Delay(200);
		 READ_BH1750(data);
		 result=DATA_DEAL(data);
		 xSemaphoreTake(semhandle,portMAX_DELAY);
		 ttinfo.light=result; 
		 xSemaphoreGive(semhandle);
		 HAL_Delay(1000);
		 //printf("-----%d----\r\n",ttinfo.light);

  }

}
void f4task(void*arg)
{


  show_oled();





}
void f5task(void*arg)
{
    while(1)
		{    
		    uploaddata();
			  osDelay(500);
		
		
		
		
		}








}
uint8_t  key_stat(void)
{
    if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_4)==0)
		{
		  while(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_4)==0);
			
			 return 1;
	
		}


    return 0;


}
void time_increase(TimerHandle_t xTimer)
{
   xSemaphoreTake(semhandle,portMAX_DELAY);
	 ttinfo.time++;
	 xSemaphoreGive(semhandle);
}
void buzzer_increase(TimerHandle_t xTimer)
{
  HAL_GPIO_TogglePin(GPIOA,GPIO_PIN_8);
}
/* USER CODE END Application */

